import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 本地存储工具类
class SharedPreferencesService extends GetxService {
  static SharedPreferencesService get to => Get.find();
  late final SharedPreferences _prefs;

  Future<SharedPreferencesService> init() async {
    _prefs = await SharedPreferences.getInstance();
    return this;
  }

  // 存储数据
  Future<bool> setString(String key, String value) {
    return _prefs.setString(key, value);
  }

  Future<bool> setInt(String key, int value) {
    return _prefs.setInt(key, value);
  }

  Future<bool> setBool(String key, bool value) {
    return _prefs.setBool(key, value);
  }

  Future<bool> setDouble(String key, double value) {
    return _prefs.setDouble(key, value);
  }

  Future<bool> setStringList(String key, List<String> value) {
    return _prefs.setStringList(key, value);
  }

  // 读取数据
  String? getString(String key) {
    return _prefs.getString(key);
  }

  int? getInt(String key) {
    return _prefs.getInt(key);
  }

  bool? getBool(String key) {
    return _prefs.getBool(key);
  }

  double? getDouble(String key) {
    return _prefs.getDouble(key);
  }

  List<String>? getStringList(String key) {
    return _prefs.getStringList(key);
  }

  /// 保存数据
  /// String、StringList、Int、Double、Bool
  Future<void> setKeyValue(String key, Object value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    if (value is String) {
      prefs.setString(key, value);
    } else if (value is List<String>) {
      prefs.setStringList(key, value);
    } else if (value is int) {
      prefs.setInt(key, value);
    } else if (value is double) {
      prefs.setDouble(key, value);
    } else if (value is bool) {
      prefs.setBool(key, value);
    }
  }

  /// 获取所有的key
  Future<Set<String>> getKeys() {
    return SharedPreferences.getInstance().then((prefs) {
      return prefs.getKeys();
    });
  }

  /// 删除数据
  Future<void> remove(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove(key);
  }

  /// 清空所有缓存数据
  Future<void> clear(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.clear();
  }
}
